package logic

import (
	"context"
	"encoding/json"
	"medical-management-system/models/cahce"
	"medical-management-system/models/mysql"
	"time"

	"medical-management-system/medicalrpc/internal/svc"
	"medical-management-system/medicalrpc/medicalrpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type ListDoctorLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewListDoctorLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ListDoctorLogic {
	return &ListDoctorLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *ListDoctorLogic) ListDoctor(in *medicalrpc.ListDoctorRequest) (*medicalrpc.ListDoctorResponse, error) {
	// todo: add your logic here and delete this line

	var doctor []mysql.Doctor
	mysql.DB.Debug().Find(&doctor)

	get, _ := cahce.Rdb.Get(l.ctx, "doctorList").Result()
	if get == "" {

		marshal, _ := json.Marshal(&doctor)

		cahce.Rdb.Set(l.ctx, "doctorList", marshal, time.Minute*30)
	} else {
		json.Unmarshal([]byte(get), &get)
	}

	var doctorList []*medicalrpc.ListDoctor

	for _, m := range doctor {
		list := medicalrpc.ListDoctor{
			Name:       m.Name,
			Department: m.Department,
			Scheduling: m.Scheduling,
		}
		doctorList = append(doctorList, &list)
	}

	return &medicalrpc.ListDoctorResponse{List: doctorList}, nil
}
